﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using ConexionAdmin;

namespace Admin
{
    class RequestManager
    {
        public AdminForm ventana = null;
        private Config conf = null;
        private IServicioAdmin remoto = null;

        public RequestManager(Config conf, AdminForm form)
        {
            this.conf = conf;
            this.ventana = form;

            String conn = "tcp://" + conf.Ip_manager + ":" + conf.Puerto_manager + "/Admin";
            //TcpChannel chan = new TcpChannel();
            //ChannelServices.RegisterChannel(chan, false);

            remoto = (IServicioAdmin)Activator.GetObject(typeof(IServicioAdmin), conn);
        }      

        public void AgregarServidorManager()
        {
            try
            {
                Label lbl = (Label)ObtenerControl("lblResultado");// lbl = (Label)ObtenerControl("lblResultado2");
                
                bool exito = remoto.AgregarServidor(ObtenerControl("txtNombreAgregar").Text, ObtenerControl("txtIPAgregar").Text,
                    int.Parse(ObtenerControl("txtPuertoAgregar").Text));

                if (exito)
                {
                    lbl.ForeColor = Color.Green;
                    lbl.Text = "Exito";
                }
                else
                {
                    lbl.ForeColor = Color.Red;
                    lbl.Text = "Error";
                }
            }
            catch (Exception)
            {
                MessageBox.Show("No se pudo realizar conexion con el manager");
            }

        }

        public void QuitarServidorManager()
        {
            try
            {
                Label lbl = (Label)ObtenerControl("lblResultado2");

                bool exito = remoto.QuitarServidor(ObtenerControl("txtIpQuitar").Text, int.Parse(ObtenerControl("txtPuertoQuitar").Text));

                if (exito)
                {
                    lbl.ForeColor = Color.Green;
                    lbl.Text = "Exito";
                }
                else
                {
                    lbl.ForeColor = Color.Red;
                    lbl.Text = "Error";
                }
            }
            catch (Exception)
            {
                MessageBox.Show("No se pudo realizar conexion con el manager");
            }

        }

        private Control ObtenerControl(string cmd)
        {
            Control[] controles = ventana.Controls.Find(cmd, true);

            return controles[0];
        }

    }
}
